package main

import (
	"strings"
)

func AddBraces_TabOr4Space(s string) string {
	// replace tab to "    "
	s = strings.ReplaceAll(s, "\t", "    ")
	return AddBraces_4space(s)
}

func getBraceLine_tab(indent int, brace string) string {
	var result string
	for i := 0; i < indent; i++ {
		result += "\t"
	}
	return result + brace
}

func AddBraces_tab(s string) string {
	lines := strings.Split(s, "\n")
	var result []string
	indentLevel := 0
	for _, line := range lines {
		indent := len(line) - len(strings.TrimLeft(line, "\t"))
		if indent > indentLevel {
			result = append(result, getBraceLine_tab(indentLevel, "{"))
			indentLevel = indent
		} else if indent < indentLevel {
			for j := indentLevel - 1; j >= indent; j-- {
				result = append(result, getBraceLine_tab(j, "}"))
			}
			indentLevel = indent
		}
		result = append(result, line)
	}
	for i := 0; i < indentLevel; i++ {
		result = append(result, getBraceLine_tab(indentLevel-i-1, "}"))
	}
	return strings.Join(result, "\n")
}

func getBraceLine_4space(indent int, brace string) string {
	var result string
	for i := 0; i < indent; i++ {
		result += "    "
	}
	return result + brace
}

func AddBraces_4space(s string) string {
	lines := strings.Split(s, "\n")
	var result []string
	indentLevel := 0
	for _, line := range lines {
		indent := len(line) - len(strings.TrimLeft(line, " "))
		indent = indent / 4
		if indent > indentLevel {
			result = append(result, getBraceLine_4space(indentLevel, "{"))
			indentLevel = indent
		} else if indent < indentLevel {
			for j := indentLevel - 1; j >= indent; j-- {
				result = append(result, getBraceLine_4space(j, "}"))
			}
			indentLevel = indent
		}
		result = append(result, line)
	}
	for i := 0; i < indentLevel; i++ {
		result = append(result, getBraceLine_4space(indentLevel-i-1, "}"))
	}
	return strings.Join(result, "\n")
}
